package com.yoomiito.app.ui.my;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;

import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.PopupWindow;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.scrat.app.selectorlibrary.ImageSelector;
import com.yoomiito.app.R;
import com.yoomiito.app.base.App;
import com.yoomiito.app.base.BaseActivity;
import com.yoomiito.app.model.my.MyUserInfo;
import com.yoomiito.app.present.my.activity.MyUserInfoPresenter;
import com.yoomiito.app.utils.AllUtils;
import com.yoomiito.app.utils.L;
import com.yoomiito.app.utils.ResUtil;
import com.yoomiito.app.utils.Type;
import com.yoomiito.app.utils.UserInfoConfig;
import com.yoomiito.app.utils.YMToast;
import com.yoomiito.app.widget.CircleImageView;
import com.yoomiito.app.widget.ItemView;
import com.yoomiito.app.widget.TipDialog;
import com.yoomiito.app.widget.TitleView;
import com.yoomiito.app.widget.dialog.CustomDialog;
import com.yoomiito.app.widget.dialog.CustomDialog1;
import com.yoomiito.app.widget.wheelview.DateSelectDialog;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class MyUserInfoActivity extends BaseActivity<MyUserInfoPresenter> {
    @BindView(R.id.act_my_user_info_title)
    TitleView titleIv;
    @BindView(R.id.iv_mine)
    CircleImageView mPhotoIv;
    @BindView(R.id.iv_name)
    ItemView mNameIv;
    @BindView(R.id.iv_sex)
    ItemView mSexIv;
    @BindView(R.id.iv_birth)
    ItemView mBirthIv;
    @BindView(R.id.iv_tel)
    ItemView mTelIv;
    @BindView(R.id.iv_wx_nick)
    ItemView mWXNickNameIv;
    @BindView(R.id.iv_taobao_nick)
    ItemView mTaobaoNickNameIv;
    @BindView(R.id.iv_member_grade)
    ItemView mMemberGradeIv;
    @BindView(R.id.iv_invite_code)
    ItemView mInviteCodeIv;
    @BindView(R.id.iv_inviter)
    ItemView mInviterIv;

    TipDialog dialog;
    private DateSelectDialog mDateDialog;
    private String[] mSex = {"男", "女"};
    private String name;
    private int sex;
    private String birthdaty;
    private String picPath;
    private MyUserInfo mMyUserInfo;
    private int REQUEST_SELECT_IMAGES_CODE = 7;
    private static int REQUEST_PHOTO_CODE = 8;
    private CustomDialog1 mCustomDialog;

    @Override
    public int getLayoutId() {
        return R.layout.activity_my_user_info;
    }

    @Override
    public MyUserInfoPresenter newP() {
        return new MyUserInfoPresenter(App.mAppConfig);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        getP().getUserInfoData();
    }

    public void setUserInfo(MyUserInfo info) {
        mMyUserInfo = info;
        sex = info.getSex()==0?0:info.getSex();
        RequestOptions requestOptions = new RequestOptions();
        requestOptions.placeholder(R.drawable.goods_default);
        Glide.with(this).load(Uri.parse(info.getHeadimgurl())).apply(requestOptions).into(mPhotoIv);
        mNameIv.setRightText(info.getName());
        if (!TextUtils.isEmpty(info.getSexShow())) {
            mSexIv.setRightText(info.getSexShow());
            mSexIv.setRightTextColor(ResUtil.getColor(R.color.color_balk_333333));
        }
        if (!TextUtils.isEmpty(info.getBirthday())) {
            mBirthIv.setRightText(info.getBirthday());//
            mBirthIv.setRightTextColor(ResUtil.getColor(R.color.color_balk_333333));
        }
//        mTelIv.setRightText(AllUtils.telHandle(info.getMobile()));
        mTelIv.setRightText(info.getMobile());
        if (!TextUtils.isEmpty(info.getTaobaoName())) {
            mTaobaoNickNameIv.setRightText(info.getTaobaoName());
            mTaobaoNickNameIv.setRightTextColor(ResUtil.getColor(R.color.color_balk_333333));
        }
        if (!TextUtils.isEmpty(info.getNickname())) {
            mWXNickNameIv.setRightText(info.getNickname());
            mWXNickNameIv.setRightTextColor(ResUtil.getColor(R.color.color_balk_333333));
        }
//        if (UserInfoConfig.getCompanyId() == 1) {

        //区代 都显示运营中心
        if (UserInfoConfig.getRoleId() >= Type.LevelType.VIP_50) {
            mMemberGradeIv.setRightText("运营中心");//
        } else {
            mMemberGradeIv.setRightText(info.getRole());//
        }
//        } else {
//            if (UserInfoConfig.getRoleId() >= LevelType.VIP_50) {
//                mMemberGradeIv.setRightText("商务董事");//
//            } else {
//                mMemberGradeIv.setRightText(info.getRole());//
//            }
//        }


//        if (UserInfoConfig.getRoleId() < LevelType.VIP_7) {
//            mMemberGradeIv.setDesRightText("可升级");
//            mMemberGradeIv.setDesRightTvColor(ResUtil.getColor(R.color.color_white));
//            mMemberGradeIv.setDesRightTvBackground(R.drawable.bg_orange_18);
//        }

        mInviteCodeIv.setRightText(info.getInvitationCode());
        mInviteCodeIv.setDesRightText("复制");
        mInviteCodeIv.setDesRightTvColor(ResUtil.getColor(R.color.color_balk_999999));
        mInviteCodeIv.setDesRightTvBackground(R.drawable.bg_line_rect_22);

        mInviterIv.setRightText(info.getParentName());
    }

    @OnClick({R.id.iv_name, R.id.iv_mine, R.id.iv_sex, R.id.iv_birth, R.id.iv_member_grade, R.id.iv_invite_code})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_name:
                L.i("name: "+mMyUserInfo.getName());
                dialog = showEditDialog(ResUtil.getString(R.string.my_name),mMyUserInfo.getName(),
                        ResUtil.getString(R.string.my_save),
                        "取消",
                        new TipDialog.Dialogcallback() {

                            @Override
                            public void btnConfirm() {
                                String newName = dialog.getEditTextContent();
                                mNameIv.setRightText(newName);
                                name = newName;
                                saveInfo();
                            }

                            @Override
                            public boolean cancel() {
                                return false;
                            }
                        });
                break;
            case R.id.iv_mine:
                final String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
                StringBuilder sb = null;
                for (String permission : permissions) {
                    if (ActivityCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                        if (sb == null) {
                            sb = new StringBuilder();
                        }
                        String str = AllUtils.permissionTipMap(permission);
                        if (sb.indexOf(str) == -1) {
                            if (!TextUtils.isEmpty(sb)) {
                                sb.append("\n\n");
                            }
                            sb.append(str);
                        }
                    }
                }
                if (sb == null || TextUtils.isEmpty(sb)) {
                    AllUtils.requestPermission(MyUserInfoActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                    Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                            .subscribe(aBoolean -> {
                                if (aBoolean) {
                                    showPopueWindow();
                                } else {
                                    YMToast.showText("请打开您的相册、相机使用权限");
                                }
                            });
                }else{
                    if (mCustomDialog == null) {
                        mCustomDialog = new CustomDialog1(this, () -> {
                            AllUtils.requestPermission(MyUserInfoActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                            Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                                    .subscribe(aBoolean -> {
                                        if (aBoolean) {
                                            showPopueWindow();
                                        } else {
                                            YMToast.showText("请打开您的相册、相机使用权限");
                                        }
                                    });
                        });
                    }
                    mCustomDialog.setContent(String.valueOf(sb));
                    mCustomDialog.show();
                }

                break;
            case R.id.iv_sex:
                changeSex();
                break;
            case R.id.iv_birth:
                selectDate();
                break;
//            case R.id.iv_member_grade:
//                Router.newIntent(this)
//                        .to(WebViewActivity.class)
//                        .putInt(Constant.TYPE, AllCode.VIPRight)
//                        .launch();
//                break;
            case R.id.iv_invite_code:
                AllUtils.copyText(this, mMyUserInfo.getInvitationCode());
                YMToast.showText("复制成功");
                break;
        }
    }

    private void showPopueWindow() {
        View popView = View.inflate(this, R.layout.popupwindow_camera_need, null);
        Button bt_album = (Button) popView.findViewById(R.id.btn_pop_album);
        Button bt_camera = (Button) popView.findViewById(R.id.btn_pop_camera);
        Button bt_cancle = (Button) popView.findViewById(R.id.btn_pop_cancel);
        //获取屏幕宽高
        int weight = getResources().getDisplayMetrics().widthPixels;
        int height = getResources().getDisplayMetrics().heightPixels * 1 / 3;

        final PopupWindow popupWindow = new PopupWindow(popView, weight, height);
//        popupWindow.setAnimationStyle(R.style.anim_popup_dir);
        popupWindow.setFocusable(true);
        //点击外部popueWindow消失
        popupWindow.setOutsideTouchable(true);

        bt_album.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                startActivityForResult(i, REQUEST_SELECT_IMAGES_CODE);
                //相册
                ImageSelector.show(context, REQUEST_SELECT_IMAGES_CODE, 1);
                popupWindow.dismiss();

            }
        });
        bt_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                getP().takeCamera(REQUEST_PHOTO_CODE);
                popupWindow.dismiss();

            }
        });
        bt_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();

            }
        });
        //popupWindow消失屏幕变为不透明
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });
        //popupWindow出现屏幕变为半透明
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        popupWindow.showAtLocation(popView, Gravity.BOTTOM, 0, 50);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_SELECT_IMAGES_CODE && resultCode == RESULT_OK) {
            List<String> imagePaths = ImageSelector.getImagePaths(data);
            picPath = imagePaths.get(0);
            RequestOptions requestOptions = new RequestOptions();
            requestOptions.placeholder(R.drawable.goods_default);
            File file = new File(picPath);
            Glide.with(App.getApplication()).load(file).apply(requestOptions).into(mPhotoIv);
            saveInfo();
        } else if (requestCode == REQUEST_PHOTO_CODE && resultCode == RESULT_OK) {
            picPath = getP().getmCurrentPhotoPath();
            RequestOptions requestOptions = new RequestOptions();
            requestOptions.placeholder(R.drawable.goods_default);
            File file = new File(picPath);
            Glide.with(App.getApplication()).load(file).apply(requestOptions).into(mPhotoIv);
            saveInfo();
        }
    }

    //1为男性，2为女性 0 默认
    private void changeSex() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.Theme_AppCompat_Light_Dialog_Alert);
        builder.setTitle("选择性别")
                .setSingleChoiceItems(mSex, sex-1, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        mSexIv.setRightText(mSex[which]);
                        mSexIv.setRightTextColor(ResUtil.getColor(R.color.color_balk_333333));
                        sex = which + 1;
                        saveInfo();
                    }
                })
                .show();
    }

    private void selectDate() {
        if (mDateDialog == null) {
            mDateDialog = new DateSelectDialog(this);
            mDateDialog.setStartYear(1970)
                    .setmHeight(200)
                    .setListener(new DateSelectDialog.OnDateWheelViewListener() {
                        @Override
                        public void onResult(String date) {
                            birthdaty = date;
                            mBirthIv.setRightText(date);
                            mBirthIv.setRightTextColor(ResUtil.getColor(R.color.color_balk_333333));
                            saveInfo();
                        }
                    });
        }
        mDateDialog.show();
    }

    public void saveInfo() {
        showLoading();
        if (TextUtils.isEmpty(picPath)) {
            getP().setUserInfoData(name, sex, birthdaty, picPath);
        } else {
            getP().uploadPhotos(name, sex, birthdaty, picPath);
        }
    }

    public void uploadSuccess(){
        picPath = null;
    }

    private Bitmap compressPixel(String filePath) {
        Bitmap bmp = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        //setting inSampleSize value allows to load a scaled down version of the original image
        options.inSampleSize = 2;

        //inJustDecodeBounds set to false to load the actual bitmap
        options.inJustDecodeBounds = false;
        options.inTempStorage = new byte[16 * 512];
        try {
            //load the bitmap from its path
            bmp = BitmapFactory.decodeFile(filePath, options);
            if (bmp == null) {

                InputStream inputStream = null;
                try {
                    inputStream = new FileInputStream(filePath);
                    BitmapFactory.decodeStream(inputStream, null, options);
                    inputStream.close();
                } catch (FileNotFoundException exception) {
                    exception.printStackTrace();
                } catch (IOException exception) {
                    exception.printStackTrace();
                }
            }
        } catch (OutOfMemoryError exception) {
            exception.printStackTrace();
        } finally {
            return bmp;
        }
    }

}
